package com.bysc.executor.handler;

import com.alibaba.fastjson.JSON;
import com.bysc.baseservice.config.RabbitmqConfig;
import com.bysc.commonutils.enums.NoticeEnum;
import com.bysc.commonutils.message.NotificationMessage;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Slf4j
public class NoticeSendJobHandler {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发布系统通知，设定发布时间，设置发布对象（协会内部成员，全体用户），定时任务，到点发送
     */
    @XxlJob("NoticeSendJob")
    public void NoticeSendJob() throws Exception {

        try {
            //TODO
            System.out.println("NoticeSendJob执行了.... " + LocalDateTime.now());
            // 获取参数
            String param = XxlJobHelper.getJobParam();
            String[] methodParams = param.split(",");

            String userId = methodParams[0]; // 目标用户: 0-所有用户 1-协会成员 其它-特定用户
            String content = methodParams[1]; // 通知内容
            String nickName = "系统";
            if ("1".equals(userId))  {
                nickName = "软件协会";
            }
            // 构建通知消息
            NotificationMessage notificationMessage = new NotificationMessage("", userId, "", content, null, NoticeEnum.SYSTEM);
            String message = JSON.toJSONString(notificationMessage);
            // 发送到RabbitMQ
            try {
                rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_TOPICS_INFORM, "inform.notice", message);
            } catch (AmqpException e) {
                throw new RuntimeException(e);
            }
            System.out.println("NoticeSendJob执行结束了.... " + LocalDateTime.now());
            //写日志到调度中心日志中
            XxlJobHelper.log("NoticeSendJob execute Success...");
            // 设置任务结果
            XxlJobHelper.handleSuccess();
        } catch (Exception e) {
            log.error("NoticeSendJob execute Fail ...", e);

            //写日志到调度中心日志中
            XxlJobHelper.log("NoticeSendJob execute Fail...");
            // 设置任务结果
            XxlJobHelper.handleFail();
        }

    }
}

